﻿using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Actions;
using DevExpress.Persistent.Base;
using EasyXaf.EntityDesigner.BusinessObjects.Entities;
using EasyXaf.EntityDesigner.BusinessObjects.Enums;
using EasyXaf.EntityDesigner.CodeTemplates;

namespace EasyXaf.EntityDesigner.Controllers;

public class GenerateCodeViewController : ViewController
{
    private SimpleAction GenerateCodeAction { get; }

    public GenerateCodeViewController()
    {
        GenerateCodeAction = new SimpleAction(this, $"{Name}-{nameof(GenerateCodeAction)}", PredefinedCategory.View)
        {
            Caption = "生成代码",
            ImageName = "Action_Export_ToHTML",
            SelectionDependencyType = SelectionDependencyType.RequireSingleObject,
        };
    }

    protected override void OnViewChanged()
    {
        var objectType = View.ObjectTypeInfo.Type;
        Active[Name] = objectType == typeof(Entity) || objectType == typeof(Enumeration);

        base.OnViewChanged();
    }

    protected override void OnActivated()
    {
        base.OnActivated();

        GenerateCodeAction.Execute += GenerateCodeAction_Execute;
    }

    protected override void OnDeactivated()
    {
        GenerateCodeAction.Execute -= GenerateCodeAction_Execute;

        base.OnDeactivated();
    }

    private void GenerateCodeAction_Execute(object sender, SimpleActionExecuteEventArgs e)
    {
        string code = string.Empty;

        if (View.CurrentObject is Entity entity)
        {
            var entityTemplate = new XpoEntityTemplate(entity);
            code = entityTemplate.GenerateCode();
        }
        else if (View.CurrentObject is Enumeration enumeration)
        {
            var enumTemplate = new EnumTemplate(enumeration);
            code = enumTemplate.GenerateCode();
        }

        if (!string.IsNullOrWhiteSpace(code))
        {
            var objectSpace = Application.CreateObjectSpace(typeof(CSharpCodeObject));
            var csharpCodeObject = objectSpace.CreateObject<CSharpCodeObject>();
            csharpCodeObject.Code = code;
            var view = Application.CreateDetailView(objectSpace, csharpCodeObject);
            Application.ShowViewStrategy.ShowViewInPopupWindow(view);
        }
    }
}
